<template>
  <div>
    <el-select v-model="selectedProvince" placeholder="请选择省份" @change="handleProvinceChange">
      <el-option v-for="province in provinces" :key="province.code" :label="province.province"
        :value="province.province" />
    </el-select>
    <el-select v-model="selectedCity" placeholder="请选择城市" :disabled="!selectedProvince" @change="handleCityChange">
      <el-option v-for="city in currentCities" :key="city.code" :label="city.city" :value="city.city" />
    </el-select>
    <el-select v-model="selectedCounty" placeholder="请选择县区" :disabled="!selectedCity" @change="handleChange">
      <el-option v-for="county in currentCounties" :key="county.code" :label="county.area" :value="county.area" />
    </el-select>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import areaData from "@/assets/areaData.json";

// 省份数据直接使用areaData
const provinces = areaData;

const props = defineProps({
  modelValue: {
    type: Array,
    default: []
  }
})

watch(() => props.modelValue, () => {
  if (props.modelValue.length === 3) {
    selectedProvince.value = props.modelValue[0];
    selectedCity.value = props.modelValue[1];
    selectedCounty.value = props.modelValue[2];
  } else {
    selectedProvince.value = "";
    selectedCity.value = "";
    selectedCounty.value = "";
  }
},);

const emits = defineEmits(["update:modelValue"]);

// 选中的省份、城市、县区
const selectedProvince = ref("");
const selectedCity = ref("");
const selectedCounty = ref("");

// 当前显示的城市列表
const currentCities = computed(() => {
  if (!selectedProvince.value) return [];
  const province = provinces.find(p => p.province === selectedProvince.value);
  return province ? province.citys : [];
});

// 当前显示的县区列表
const currentCounties = computed(() => {
  if (!selectedCity.value) return [];
  const province = provinces.find(p => p.province === selectedProvince.value);
  if (!province) return [];
  const city = province.citys.find(c => c.city === selectedCity.value);
  return city ? city.areas : [];
});

// 处理省份选择变化
const handleProvinceChange = () => {
  selectedCity.value = "";
  selectedCounty.value = "";
};

// 处理城市选择变化
const handleCityChange = () => {
  selectedCounty.value = "";
};

const handleChange = () => {
  emits("update:modelValue", [selectedProvince.value, selectedCity.value, selectedCounty.value]);
}

// 暴露选中的值给父组件
defineExpose({
  selectedProvince,
  selectedCity,
  selectedCounty
});
</script>
<style lang="scss" scoped>
/* 可根据需要添加样式 */
</style>
